<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="128">
      <el-form-item label="筛板编号" prop="deviceCode">
        <el-input
          v-model="queryParams.deviceCode"
          placeholder="请输入筛板编号"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="筛板EPC编号" prop="epcs">
        <el-input
          v-model="queryParams.epcs"
          placeholder="请输入筛板EPC编号"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="Plus"
          @click="handleAdd"
          v-hasPermi="['manager:rfid:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
            type="primary"
            plain
            icon="Search"
            @click="epcUselessOpen"
        >出厂检验</el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="rfidList" @selection-change="handleSelectionChange">
      <el-table-column label="序号" align="center" prop="id" width="60" />
      <el-table-column label="筛板编号" align="center" prop="deviceCode" width="120"/>
      <el-table-column label="筛板epcs编号" align="center" prop="epcs" width="235" :show-overflow-tooltip="true" />
      <el-table-column label="在线筛板epc编号" align="center" prop="onlineEpc" width="240" :show-overflow-tooltip="true" />
      <el-table-column label="安装位置" align="center" prop="serialNumber" width="80" />
      <el-table-column label="在线状态" align="center" prop="status" width="80">
        <template #default="scope">
          <el-tag
            v-if="scope.row.status === 'online'"
            :type="scope.row.status === 'online' ? 'success' : ''"
            disable-transitions> 在线 </el-tag>
          <el-tag
            v-else-if="scope.row.status === 'offline'"
            :type="scope.row.status === 'offline' ? 'danger' : ''"
            disable-transitions> 离线 </el-tag>
          <el-tag
            v-else
            type="info"
            disable-transitions> 未知 </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="检测状态" align="center" prop="detectionStatus" width="80">
        <template #default="scope">
          <el-tag
            v-if="scope.row.detectionStatus === true"
            :type="scope.row.detectionStatus === true ? 'primary' : ''"
            disable-transitions> 检测 </el-tag>
          <el-tag
            v-else-if="scope.row.detectionStatus === false"
            :type="scope.row.detectionStatus === false ? 'info' : ''"
            disable-transitions> 暂不检测 </el-tag>
          <el-tag
            v-else
            type="info"
            disable-transitions> 未知 </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="生产日期" align="center" prop="produceTime" width="160" >
        <template #default="scope">
          <span>{{ parseTime(scope.row.produceTime, '{y}-{m}-{d} {h}:{i}:{s}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="安装时间" align="center" prop="installTime" width="160">
        <template #default="scope">
          <span>{{ parseTime(scope.row.installTime, '{y}-{m}-{d} {h}:{i}:{s}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="150">
        <template #default="scope">
          <el-button
            link type="primary"
            icon="Edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['manager:rfid:edit']"
          >修改</el-button>
          <el-button
            link type="danger"
            icon="Delete"
            v-hasPermi="['manager:productInfo:remove']"
            @click="handleDelete(scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改rfid记录对话框 -->
    <el-dialog :title="title" v-model="open" width="500px" append-to-body>
      <el-form ref="rfidRef" :model="form" :rules="rules" label-width="108px">

        <el-form-item label="筛板编号" prop="deviceCode">
          <el-input v-model="form.deviceCode" placeholder="请输入筛板EPC编号" @keyup="setEpcs" @focus="setEpcs" />
        </el-form-item>
        <el-form-item label="筛板EPC编号" prop="epcs">
          <el-input v-model="form.epcs"
                    readonly
                    placeholder="请输入筛板EPC编号"
                    show-word-limit
                    type="textarea"
                    :autosize="{ minRows: 3, maxRows: 6 }"/>
        </el-form-item>

        <el-form-item label="检测状态" prop="detectionStatus">
          <el-radio-group v-model="form.detectionStatus">
            <el-radio :label="true">检测</el-radio>
            <el-radio :label="false">暂不检测</el-radio>
          </el-radio-group>
        </el-form-item>

        <el-form-item label="安装位置" prop="serialNumber">
          <el-input v-model="form.serialNumber" placeholder="请输入安装位置" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
    <el-dialog title="未录入编号" :before-close="epcUselessCancel" v-model="epcUseless" width="500px" append-to-body>
      <el-form ref="rfidRef" :model="epcUselessForm" label-width="108px">
        <el-form-item label="筛板编号" prop="epcs">
          <el-input v-model="epcUselessForm.onlineEpc"
                    readonly
                    placeholder="未检测到筛板编号"
                    show-word-limit
                    type="textarea"
                    :autosize="{ minRows: 3, maxRows: 6 }"/>
        </el-form-item>
        <el-form-item label="读秒" >
          <el-input v-model="epcUselessForm.countingSeconds" readonly  />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="epcUselessClear">清 空</el-button>
          <el-button type="primary" icon="Refresh" @click="epcUselessQueryIntervalStart">{{buttonValue}}</el-button>
          <el-button circle icon="Refresh" @click="epcUselessQuery()" />
          <el-button @click="epcUselessCancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="Rfid">
import {
  getRfid,
  listRfid,
  updateRfidCustomer,
  addRfidCustomer,
  removeRfidCustomer,
  epcUselessList, epcUselessClearRequst
} from "@/api/manager/rfid";
import {ref} from "vue";

const { proxy } = getCurrentInstance();

const rfidList = ref([]);
const open = ref(false);
const epcUseless = ref(false);
const epcUselessTimer = ref(true);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
let timer = ref<String>("");
let timer1 = ref<String>("");
const buttonValue = ref("暂停刷新");
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const title = ref("");

const data = reactive({
  form: {},
  epcUselessForm: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    parentId: null,
    deviceId: null,
    deviceCode: null,
    epcs: null,
    onlineEpc: null,
    model: null,
    serialNumber: null,
    status: null,
    detectionStatus: null,
    produceTime: null,
    installTime: null,
    reportTime: null,
    deleted: null,
  },
  rules: {
    deviceCode: [
      { required: true, message: "筛板编号不能为空", trigger: "blur" }
    ],
    epcs: [
      { required: true, message: "筛板EPC编号不能为空", trigger: "blur" }
    ],
    serialNumber: [
      { required: true, message: "筛板安装位置不能为空", trigger: "blur" }
    ],
    detectionStatus: [
      { required: true, message: "筛板检测状态不能为空", trigger: "blur" }
    ],
  }

});

const { queryParams, form, rules,epcUselessForm } = toRefs(data);

/** 查询rfid记录列表 */
function getList() {
  loading.value = true;
  listRfid(queryParams.value).then(response => {
    rfidList.value = response.rows;
    total.value = response.total;
    loading.value = false;
    console.log("rfidList",rfidList.value)
  }).catch(e=>{
    loading.value = false;
  });
}

// 取消按钮
function cancel() {
  open.value = false;
  reset();
}

// 表单重置
function reset() {
  form.value = {
    id: null,
    parentId: null,
    deviceId: null,
    deviceCode: null,
    epcs: null,
    onlineEpc: null,
    model: null,
    serialNumber: null,
    status: null,
    detectionStatus: true,
    produceTime: null,
    installTime: null,
    reportTime: null,
    deleted: null,
    createTime: null,
    createBy: null,
    updateTime: null,
    updateBy: null,
    remark: null
  };
  proxy.resetForm("rfidRef");
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}


/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef");
  handleQuery();
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.id);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}

/** 新增按钮操作 */
function handleAdd() {
  reset();
  open.value = true;
  title.value = "添加rfid记录";
}

function epcUselessQuery() {
  epcUselessList(queryParams.value).then(response => {
    epcUselessForm.value.onlineEpc = response.data.onlineEpc;
  }).catch(e=>{
    loading.value = false;
  });
}
function epcUselessOpen() {
  epcUseless.value = true;
  epcUselessQueryIntervalStart();
}


function epcUselessQueryIntervalStart() {
  if (epcUselessTimer.value) {
    epcUselessTimer.value=false;
    buttonValue.value="暂停刷新"
    epcUselessForm.value.countingSeconds = 0;
    timer=setInterval(() => {
      epcUselessQuery()
    }, 1000);
    timer1=setInterval(() => {
      epcUselessForm.value.countingSeconds+=1;
    }, 1000);
  }else {
    epcUselessQueryIntervalStop();
    buttonValue.value="实时刷新"
    epcUselessTimer.value=true;
  }
}
function epcUselessQueryIntervalStop() {
  clearInterval(timer);
  clearInterval(timer1);
  epcUselessTimer.value=true;
}

function epcUselessCancel() {
  epcUseless.value = false;
  epcUselessQueryIntervalStop();
  epcUselessReset();


}
function epcUselessReset() {
  epcUselessForm.value = {
    epcs: null,
    countingSeconds: 0
  };
}

function epcUselessClear() {
  epcUselessReset();
  epcUselessClearRequst(queryParams.value);
}


/** 修改按钮操作 */
function handleUpdate(row) {
  reset();
  const _id = row.id || ids.value
  getRfid(_id).then(response => {
    form.value = response.data;
    setEpcs()
    open.value = true;
    title.value = "修改rfid记录";
  });
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["rfidRef"].validate(valid => {
    if (valid) {
      if (form.value.id != null) {
        updateRfidCustomer(form.value).then(response => {
          proxy.$modal.msgSuccess("修改成功");
          open.value = false;
          getList();
        });
      } else {
        addRfidCustomer(form.value).then(response => {
          proxy.$modal.msgSuccess("新增成功");
          open.value = false;
          getList();
        });
      }
    }
  });
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _id = row.id || ids.value;
  proxy.$modal.confirm('是否确认删除筛板编号为"' + row.deviceCode + '"的数据项？').then(function() {
    return removeRfidCustomer(_id);
  }).then(() => {
    getList();
    proxy.$modal.msgSuccess("删除成功");
  }).catch(() => {});
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download('manager/rfid/export', {
    ...queryParams.value
  }, `rfid_${new Date().getTime()}.xlsx`)
}

function setEpcs(){
  if (form.value.deviceCode){
    let epcA = form.value.deviceCode+'a,'
    let epcB = form.value.deviceCode+'b,'
    let epcC = form.value.deviceCode+'c'
    form.value.epcs = epcA + epcB + epcC
  }

}
getList();
</script>
